<template>
    <div>
        <Modal v-model="show" title="权限分配"
               :mask-closable="false" :closable="false">
            <Tree :data="permissionData" ref="tree" show-checkbox></Tree>
            <div slot="footer">
                <Button type="default" :disabled="loading" @click="cancel(false)">取消</Button>
                <Button type="primary" :loading="loading" @click="ok">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {mapActions} from 'vuex';

    export default {
        data() {
            return {
                show: true,
                loading: false,
                permissionData: []
            };
        },
        props: {
            roleId: {
                type: String,
                default: ''
            }
        },
        methods: {
            ...mapActions(['getPermission', 'assignPermission']),
            ok() {
                this.loading = true;
                let checkData = this.$refs.tree.getCheckedNodes();
                let arr = [];
                for (let i = 0; i < checkData.length; i++) {
                    arr.push(checkData[i].id);
                }
                this.assignPermission({
                    roleId: this.roleId,
                    data: arr
                }).then(res => {
                    if (res.code === '0000') {
                        this.$Message.success(this.$t('operatorSuccess'));
                        this.cancel(true);
                    } else {
                        this.$Message.error(this.$t('systemError'));
                    }
                    this.loading = false;
                });
            },
            cancel(reload = false) {
                this.$emit('cancel', 'assign', reload);
            },
            loadData() {
                this.getPermission({}).then(res => {
                    if (res.code === '0000') {
                        this.permissionData = res.data;
                    } else {
                        this.$Message.error(this.$t('queryDataFailed'));
                    }
                });
            }
        },
        created() {
            this.loadData();
        }
    };
</script>

<style scoped>

</style>